/*
 * Copyright (C) 2011 xjuraj
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sk.lieskove.jianghongtiao.websearch.document.preprocessing.actions;

import org.apache.log4j.Logger;
import sk.lieskove.jianghongtiao.common.utils.FileUtils;
import sk.lieskove.jianghongtiao.common.utils.PropertiesUtils;
import sk.lieskove.jianghongtiao.websearch.document.preprocessing.converter.ConverterManager;
import sk.lieskove.jianghongtiao.websearch.persistence.WebSearchResponse;

import java.io.*;
import java.util.Scanner;

/**
 *
 * @author xjuraj
 */
public class Txt2Word implements PreprocessAction{

    private Logger log = Logger.getLogger(Pdf2Txt.class);
    private PropertiesUtils pu = new PropertiesUtils(Pdf2Txt.class);
    
    @Override
    public WebSearchResponse preprocess(WebSearchResponse response) {
        log.debug("Txt2Word: WebSearchResponse preprocess(WebSearchResponse response) ");
        if(response.getFile() == null){
            return response;
        }
        ConverterManager cm = new ConverterManager();
        log.debug("File: "+response.getFile().getAbsolutePath());
        File result = FileUtils.getTempFile("Txt2Word_", "");
        Writer w = null;
        Scanner s = null;
        try {
            w = new OutputStreamWriter(new FileOutputStream(result));
            s = new Scanner(response.getFile());
            while(s.hasNext()){
                String word = cm.applyAll(s.next());
                if(!word.equals("")){
                    w.write(word);
                    w.write(" ");
                }
            }
            
        } catch (FileNotFoundException ex) {
            log.error("File was not found: "+response.getFile());
        } catch (IOException ex) {
            log.error("IO exception during word extraction!");
        } finally {
            try {
                w.close();
            } catch (IOException ex) {
                log.error("Cannot close output stream!");
            }
            s.close();
        }
        response.setFile(result);
        return response;
    }
    
}
